<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Theme } from '@/api/modules/theme'
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import api from '@/api/modules/theme'
import useSettingsStore from '@/store/modules/settings'
import { QuillEditor } from '@vueup/vue-quill'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 富文本框
const quillEditorRef = ref<InstanceType<typeof QuillEditor>>()
const quillEditorEnRef = ref<InstanceType<typeof QuillEditor>>()

// 特殊字符检验
const validateNoSpecialChars = (value: string) => {
  // 允许字母、数字、汉字、空格、基本标点和中英文逗号，以及 - _ .
  return /[#$%&?]/.test(value) // 移除了 - _ .
}

// 百度翻译接口
const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}
const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}

const isEditable = ref(false) // 控制是否可编辑的标志
const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const translating = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  themeId: route.params.id as string | number ?? '',
  themeName: '',
  themeNameEn: '',
  themeTitle: '',
  activityDescription: '',
  activityDescriptionEn: '',
  themeUrl: '',
  expectStartTime: '',
  overTime: '',
  themeType: '',
  activityIntroduction: '',
  activityIntroductionEn: '',
})

const translateThemeNameToEnglish = async () => {
  if (form.value.themeName && form.value.themeName.trim() !== '') {
    form.value.themeNameEn = await translateToEnglish(form.value.themeName)
  }
}

const translateActivityIntroductionToEnglish = async () => {
  if (form.value.activityIntroduction && form.value.activityIntroduction.trim() !== '') {
    form.value.activityIntroductionEn = await translateToEnglish(form.value.activityIntroduction)
  }
}

const translateActivityDescriptionToEnglish = async () => {
  try {
    translating.value = true
    if (form.value.activityDescription && form.value.activityDescription.trim() !== '') {
      // 获取当前富文本的HTML内容
      const htmlContent = form.value.activityDescription

      // 翻译HTML内容（保留格式）
      const translatedHtml = await translateText(htmlContent, 'zh', 'en')

      // 将翻译结果设置到英文富文本
      form.value.activityDescriptionEn = translatedHtml

      // 手动更新Quill编辑器内容（如果需要）
      await nextTick()
      quillEditorEnRef.value?.setHTML(translatedHtml)
    }
  }
  catch (error) {
    console.error('翻译失败:', error)
    ElMessage.error('翻译失败，请稍后再试')
  }
  finally {
    translating.value = false
  }
}

const formRules = ref<FormRules>({
  themeName: [
    { required: true, message: '请输入大赛活动名称', trigger: 'blur' },
    { max: 50, message: '中文名称不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  themeNameEn: [
    { required: true, message: '请输入大赛活动英文名称', trigger: 'blur' },
    { max: 250, message: '英文名称不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文名称不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  themeTitle: [
    { required: true, message: '请选择大赛主题', trigger: 'blur' },
  ],
  activityDescription: [
    { required: true, message: '请输入活动说明', trigger: 'blur' },
  ],
  activityDescriptionEn: [
    { required: true, message: '请输入活动英文说明', trigger: 'blur' },
  ],
  themeUrl: [
    { required: true, message: '请输入图片地址', trigger: 'blur' },
  ],
  expectStartTime: [
    { required: true, message: '请选择预计开始时间', trigger: 'change' },
  ],
  overTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
  ],
  themeType: [
    { required: true, message: '请选择大赛类型', trigger: 'change' },
  ],
  activityIntroduction: [
    { required: true, message: '请输入活动简介', trigger: 'blur' },
    { max: 500, message: '活动简介不能超过500个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  activityIntroductionEn: [
    { required: true, message: '请输入活动简介英文', trigger: 'blur' },
    { max: 2500, message: '简介英文不能超过2500个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文说明不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

onMounted(() => {
  if (route.name === 'themeCreate') {
    isEditable.value = true
  }
  else {
    isEditable.value = route.query.mySelf === 'true'
  }
  if (form.value.themeId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  const themeId = form.value?.themeId
  if (themeId) {
    const idNumber = Number(themeId)
    api.detail(idNumber).then((res: any) => {
      loading.value = false
      const data = res.data.data // 提取数据
      // 完整映射所有字段
      form.value.themeId = data.themeId
      form.value.themeName = data.themeName
      form.value.themeNameEn = data.themeNameEn
      form.value.themeTitle = data.themeTitle
      form.value.activityDescription = data.activityDescription
      form.value.activityDescriptionEn = data.activityDescriptionEn
      form.value.themeUrl = data.themeUrl
      form.value.expectStartTime = data.expectStartTime
      form.value.overTime = data.overTime
      form.value.themeType = data.themeType
      form.value.activityIntroduction = data.activityIntroduction
      form.value.activityIntroductionEn = data.activityIntroductionEn
    })
  }
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 格式化时间字段
        const formattedExpectStartTime = form.value.expectStartTime
          ? dayjs(form.value.expectStartTime).format('YYYY-MM-DD HH:mm:ss')
          : ''

        const formattedOverTime = form.value.overTime
          ? dayjs(form.value.overTime).format('YYYY-MM-DD HH:mm:ss')
          : ''

        // 构造符合 Theme 接口的对象
        const themeData = {
          themeId: Number(form.value.themeId),
          themeName: form.value.themeName,
          themeNameEn: form.value.themeNameEn,
          themeTitle: form.value.themeTitle,
          activityDescription: form.value.activityDescription,
          activityDescriptionEn: form.value.activityDescriptionEn,
          themeUrl: form.value.themeUrl,
          expectStartTime: formattedExpectStartTime, // 格式化后的时间
          overTime: formattedOverTime, // 格式化后的时间
          themeType: form.value.themeType,
          activityIntroduction: form.value.activityIntroduction,
          activityIntroductionEn: form.value.activityIntroductionEn,
        } as Theme

        if (form.value.themeId === '') {
          api.create(themeData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.themeId = Number(form.value.themeId)
          api.edit(themeData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}

function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'themeList' })
  }
  else {
    router.push({ name: 'themeList' })
  }
}

// 上传文件
async function handleLogoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await api.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.themeUrl = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'themeCreate' ? '新增大赛' : '编辑大赛'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="大赛名称" prop="themeName">
          <ElInput v-model="form.themeName" :disabled="!isEditable" placeholder="请输入大赛活动名称">
            <template #append>
              <ElButton v-if="isEditable" @click="translateThemeNameToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>
        <ElFormItem label="大赛英文名" prop="themeNameEn">
          <ElInput v-model="form.themeNameEn" :disabled="!isEditable" placeholder="请输入大赛活动英文名称" />
        </ElFormItem>
        <ElFormItem label="大赛主题" prop="themeTitle">
          <ElSelect v-model="form.themeTitle" :disabled="!isEditable" placeholder="请选择大赛主题">
            <ElOption label="校徽主题" value="1" />
            <ElOption label="周边主题" value="2" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="活动简介" prop="activityIntroduction">
          <ElInput v-model="form.activityIntroduction" :disabled="!isEditable" type="textarea" placeholder="请输入活动说明" />
          <div>
            <ElButton v-if="isEditable" @click="translateActivityIntroductionToEnglish">
              翻译
            </ElButton>
          </div>
        </ElFormItem>
        <ElFormItem label="活动简介英文" prop="activityIntroductionEn">
          <ElInput v-model="form.activityIntroductionEn" :disabled="!isEditable" type="textarea" placeholder="请输入活动说明" />
        </ElFormItem>
        <ElFormItem label="活动说明" prop="activityDescription">
          <div class="quill-editor-wrapper">
            <QuillEditor
              v-if="isEditable"
              ref="quillEditorRef"
              v-model:content="form.activityDescription"
              content-type="html"
              placeholder="请输入新闻内容"
              style="min-height: 200px;"
            />
            <!-- 仅预览模式 -->
            <div
              v-else
              class="ql-container ql-snow"
              style=" min-height: 200px;border: 1px solid #dcdfe6; border-radius: 4px;"
            >
              <div
                class="ql-editor"
                style="padding: 12px;" v-html="form.activityDescription"
              />
            </div>
            <ElButton
              v-if="isEditable"
              style="margin-top: 8px;"
              :loading="translating"
              @click="translateActivityDescriptionToEnglish"
            >
              翻译
            </ElButton>
          </div>
        </ElFormItem>
        <ElFormItem label="活动说明英文" prop="activityDescriptionEn">
          <div class="quill-editor-wrapper">
            <!-- 编辑模式 -->
            <QuillEditor
              v-if="isEditable"
              ref="quillEditorEnRef"
              v-model:content="form.activityDescriptionEn"
              content-type="html"
              placeholder="请输入新闻英文内容" style="min-height: 200px;"
            />
            <!-- 仅预览模式 -->
            <div
              v-else
              class="ql-container ql-snow"
              style=" min-height: 200px;border: 1px solid #dcdfe6; border-radius: 4px;"
            >
              <div
                class="ql-editor"
                style="padding: 12px;" v-html="form.activityDescriptionEn"
              />
            </div>
          </div>
        </ElFormItem>
        <ElFormItem label="宣传图" prop="themeUrl">
          <ImageUpload
            v-if="isEditable"
            v-model="form.themeUrl"
            :loading="updateImg"
            action=""
            name="themeUrl"
            :width="150"
            :height="150"
            :http-request="handleLogoSuccess"
          />
          <!-- 编辑模式使用预览组件 -->
          <div v-else class="image-preview-container">
            <ImagePreview
              :src="form.themeUrl"
              class="preview-image"
              alt="宣传图"
              :width="150"
              :height="150"
            />
          </div>
        </ElFormItem>
        <ElFormItem label="开始时间" prop="expectStartTime">
          <ElDatePicker v-model="form.expectStartTime" :disabled="!isEditable" type="datetime" placeholder="请选择预计开始时间" />
        </ElFormItem>
        <ElFormItem label="结束时间" prop="overTime">
          <ElDatePicker v-model="form.overTime" :disabled="!isEditable" type="datetime" placeholder="请选择结束时间" />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}

.quill-editor-wrapper {
  width: 100%;
  margin: 0; /* 避免多余间距 */
}

.ql-container.ql-snow {
  border: 1px solid #dcdfe6 !important;
  border-radius: 4px;
}

.ql-editor {
  min-height: 200px;
  padding: 12px;
  cursor: not-allowed;
  background-color: #f5f7fa;
}
</style>
